﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DFGK_WMS.WebAPI.Filter
{
    public class CtmLogActionFilterAttribute : Attribute, IAsyncActionFilter
    {
        private readonly ITLogRepository _LogRepository;

        public CtmLogActionFilterAttribute(ITLogRepository logRepository)
        {
            _LogRepository = logRepository;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {

             
            //当前登录人
            string currentUserName = context.HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "UserName")?.Value;
            string currentRealName = context.HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "RealName")?.Value;
            string currentUserId = context.HttpContext?.User?.Claims?.FirstOrDefault(t => t.Type == "UserId")?.Value; 
                
            //操作目标
            object? controllerName = context.HttpContext.GetRouteValue("controller");
            object? actionName = context.HttpContext.GetRouteValue("action");
           

            //参数
            string strParameter = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);


            string apiName = $"[{controllerName}-{actionName}-{strParameter}]";

            TLog log = new TLog()
            {
                CreateDate = DateTime.Now,
                Description = apiName,
                LogType = 1,
                UserName = currentUserName,
                RealName = currentRealName
             

            };

            _LogRepository.Add(log);


            await next.Invoke();
        }
    }
}
